﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace BReusable
{
   public static class UnitTesting
    {
       public static bool HasPermission(this PermissionType permissionsActual,PermissionType permissionExpected)
       {
           return permissionExpected == (permissionsActual & permissionExpected);
       }
       public static PermissionType Has_Perms_By_Name(string schemaDotTableName, PermissionType permissions,
           Func<string,IEnumerable<int>> sqlQueryFunc)
       {
           //using (var db=new LQDev202DataContext())
           //{
           PermissionType? result = null;
           var sb = new StringBuilder("select ");
           var q = new Queue<PermissionType>();
           {
               
               var first = true;
               foreach (var permission in permissions.GetAllSelectedItems<PermissionType>())
               {
                   if (!first)
                       sb.Append(',');
                   first = false;
                   q.Enqueue(permission);
                   sb.Append("has_perms_by_name ('" + schemaDotTableName
                             + "','OBJECT','" + permission.DescriptionOrToString() + "')");
               }
           }
           var queryResult = sqlQueryFunc(sb.ToString());
  
           foreach (var i in queryResult)
           {
               var permission = q.Dequeue();
               if(i==1)
               {
                   if(result==null)
                       result = permission;
                   else
                       result |= permission;
               }
              
           }
           

           //}
            // ReSharper disable PossibleNullReferenceException
           return result.Value;
            // ReSharper restore PossibleNullReferenceException
       }
       //public static PermissionType? Has_Perms_By_Name(string securable, string securableClass,
       //    string permission,Func<string,IEnumerable<int>> sqlQueryFunc)
       //{
           
       //}
    }

    [Flags]
    public enum PermissionType
    {

        Select = 1,
        Insert = 2,
        Update = 4,
        Delete = 8,
        Alter = 16,
        Execute = 32,
        [Description("View Definition")]
        ViewDefinition = 64
    }
}
